package main

import (
	"image"
	"image/draw"

	p9draw "code.google.com/p/jnj.plan9/draw"
	"code.google.com/p/jnj/cmd/util"
	"code.google.com/p/jnj/graphics"
	p9funcs "code.google.com/p/jnj/graphics/plan9"
	"code.google.com/p/jnj/graphics/text"
)

var (
	disp  *p9draw.Display
	mouse *p9draw.Mousectl
	buf   *text.Buffer
	die   = util.Die
)

func input() {
	mchan := p9funcs.SetupMouseChan(mouse)
	kchan := p9funcs.SetupKeyboardChan(disp.InitKeyboard())
	var current string
	for {
		select {
		case me := <-mchan:
			buf.MouseChan <- me
			_ = <-buf.ClickChan
		case c := <-kchan:
			if c == ' ' && len(current) > 0 {
				sug := suggest(current)
				current = ""
				for _, r := range sug[0] {
					buf.KeyboardChan <- r
				}
			} else {
				current += string(c)
				buf.KeyboardChan <- c
			}
		}
	}
}

func main() {
	var err error
	disp, err = p9draw.Init(nil, "compose", "300x200")
	die(err)
	mouse = disp.InitMouse()
	screen := disp.ScreenImage
	opts := text.Options{
		Rect:         screen.R,
		FontPath:     "/Users/jnj/Downloads/mincho.ttf",
		KeyboardChan: make(chan rune),
		MouseChan:    make(chan *graphics.MouseEvent),
		ClipChan:     p9funcs.SetupClipChan(disp),
	}
	buf, err = text.NewBuffer(opts)
	die(err)
	defer buf.Close()
	screenbuf := image.NewRGBA(screen.R)
	go input()
	for {
		select {
		case img := <-buf.DrawChan:
			draw.Draw(screenbuf, screenbuf.Rect, img, image.ZP, draw.Src)
			_, err := screen.Load(screenbuf.Rect, screenbuf.Pix)
			die(err, "error drawing to screen")
			disp.Flush()
		case <-mouse.Resize:
			err = disp.Attach(p9draw.Refmesg)
			die(err, "error reattaching screen")
			screenbuf = image.NewRGBA(screen.R)
			buf.Resize(screen.R)
		}
	}
}
